﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;

namespace DTGroup_ZheJiang.Utility
{
    public class ExcelUtil
    {
        /// <summary>
        /// 将DataTable第一行数据转化DataTable对象的Cloumn信息
        /// </summary>
        /// <param name="dataTable"></param>
        public static DataTable MapDataTableColumn(DataTable dataTable, Dictionary<string, string> columnMaps)
        {
            if (columnMaps == null || columnMaps.Count == 0)
            {
                return dataTable;
            }
            // 修改DataTable对象的Column信息
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                if (columnMaps.ContainsKey(dataTable.Columns[i].ColumnName))
                {
                    dataTable.Columns[i].ColumnName = columnMaps[dataTable.Columns[i].ColumnName];
                }
            }
            return dataTable;
        }

        public static void ListToCsv<T>(List<T> items, string headLine, string filePath, Func<T, string> work, Encoding ec = null)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                if (ec == null)
                {
                    ec = Encoding.UTF8;
                }
                using (StreamWriter sw = new StreamWriter(new BufferedStream(fs), ec))
                {
                    sw.WriteLine(headLine);

                    for (int w = 0; w < items.Count; w++)
                    {
                        if (work != null)
                        {
                            sw.WriteLine(work(items[w]));
                        }
                    }
                    sw.Close();
                    fs.Close();
                }
            }
        }
    }
}
